<?php

namespace App\Http\Services;

use App\Http\Model\Hint;
use App\Http\Model\System;
use App\Http\Model\TrendsTopic;
use App\Http\Model\Trends;
use App\Http\Model\FinanceUserWallet;
use App\Http\Model\Medal;

class TrendsTopicServices extends CommonServices
{
    protected $trendsTopicModel;
    protected $trendsModel;
    protected $financeUserWalletModel;
    protected $medalModel;
    protected $modelSystem;

    public function __construct()
    {
        parent::__construct();

        $this->trendsTopicModel = new TrendsTopic();
        $this->trendsModel = new Trends();
        $this->financeUserWalletModel = new FinanceUserWallet();
        $this->medalModel = new Medal();
        $this->modelSystem = new System();
    }

    /**
     * 获取动态话题
     * */
    public function getTrendsTopic()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('keywords', '关键字', 'string', false);
            $this->I('page', '页数', 'int', false);
            $this->I('limit', '条数', 'int', false);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            $page = $this->requestData['page'] ?? 0;
            $limit = $this->requestData['limit'] ?? 10;
            unset($this->requestData['page']);
            unset($this->requestData['limit']);

            $data = $this->trendsTopicModel->getTrendsTopic($this->requestData['keywords'] ?? '', $page, $limit);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 动态话题-获取详情
     * */
    public function getTrendsTopicDetail()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [
            'join_total_count' => 0,
            'detail' => [],
            'trends' => [],
        ];

        do {
            $this->I('user_id', '用户ID', 'int', true, '用户ID不能为空');// 当前登录用户ID
            $this->I('topic_id', '动态话题ID', 'int', true, '动态话题ID不能为空');
            $this->I('page', '页数', 'int', false);
            $this->I('limit', '条数', 'int', false);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            // 查询动态话题详情
            $data['detail'] = $this->trendsTopicModel->getTrendsTopicDetail($this->requestData['topic_id']);
            if (empty($data['detail'])) {
                break;
            }

            // 动态数据 默认10条
            $getTrendsJoinListByTopicId = $this->getTrendsJoinListByTopicId();

            $data['trends'] = $getTrendsJoinListByTopicId['data'];
            $data['join_total_count'] = $getTrendsJoinListByTopicId['data']['total_count'];

        } while (false);

        return compact('code', 'msg', 'data');
    }

    ####################################################################################################

    /**
     * 动态话题-动态参与-获取动态内容列表分页
     * */
    public function getTrendsJoinListByTopicId()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('user_id', '用户ID', 'int', true, '用户ID不能为空');// 当前登录用户ID
            $this->I('topic_id', '动态话题ID', 'int', true, '动态话题ID不能为空');
            $this->I('page', '页数', 'int', false);
            $this->I('limit', '条数', 'int', false);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            $page = $this->requestData['page'] ?? 0;
            $limit = $this->requestData['limit'] ?? 10;
            unset($this->requestData['page']);
            unset($this->requestData['limit']);

            $examine_switch = $this->modelSystem->getExamineSwitch('switch');
            // 获取参与该话题的所有动态ID数据
            $data = $this->trendsTopicModel->getTrendsJoinByTopicId($this->requestData['topic_id'], $page, $limit ,$examine_switch);
            if (empty($data['list'])) {
                break;
            }

            // 获取动态列表，根据ID获取
            $contentIdArray = array_column($data['list'], 'content_id');
            $trendsRecommendList = $this->trendsModel->trends_recommend_list(0, count($contentIdArray), 0, $contentIdArray, $this->requestData['user_id']);

            if (empty($trendsRecommendList)) {
                $data['list'] = [];
                break;
            }

            // 获取用户信息
            $this->getUserInfoByDataArray($trendsRecommendList);
            // 获取阅读数
            $this->getTrendsReadCount($trendsRecommendList);
            // 用户是否点赞
            $this->getTrendsLikeExist($trendsRecommendList);

            $data['list'] = $trendsRecommendList;

        } while (false);

        return compact('code', 'msg', 'data');
    }

    ####################################################################################################

    /**
     * 动态话题-更新或创建
     * */
    public function updateOrInsertTrendsTopic()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('topic_id', '动态话题ID', 'int', false);
            $this->I('user_id', '用户ID', 'int', false);// 话题所属用户ID，默认为0
            $this->I('topic_name', '话题名称', 'string', false);
            $this->I('topic_desc', '话题描述', 'string', false);
            $this->I('topic_image', '话题图片', 'string', false);
            $this->I('topic_type', '话题类型', 'int', false);// 默认0=无
            $this->I('topic_state', '话题状态', 'int', false);// 默认0=不公开，1=公开
            $this->I('sort', '话题排序', 'int', false);// 默认0，降序排序：100-0
            $this->I('url', '外跳链接URL', 'string', false);

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            $topicId = $this->requestData['topic_id'] ?? 0;
            unset($this->requestData['topic_id']);

            if (empty($this->requestData)) {
                $code = Hint::ERR_PARAMS_CHECK_FAIL;
                $msg = Hint::getErrCodeMsg($code) . ':至少包含任意一个业务参数';
                break;
            }

            // 更新
            if ($topicId > 0) {
                $ret = $this->trendsTopicModel->CUDTrendsTopic($this->requestData, 'update', $topicId);
                if (!$ret) {
                    $code = Hint::ERR_DATA_UPDATE_FAIL;
                    $msg = '动态话题' . Hint::getErrCodeMsg($code);
                    break;
                }
                $data['topic_id'] = $topicId;
                break;
            }

            // 创建
            $ret = $this->trendsTopicModel->CUDTrendsTopic($this->requestData, 'insert');
            if (!$ret) {
                $code = Hint::ERR_DATA_CREATE_FAIL;
                $msg = '动态话题' . Hint::getErrCodeMsg($code);
                break;
            }
            $data['topic_id'] = intval($ret);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    /**
     * 动态话题-删除
     * */
    public function removeTrendsTopic()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];

        do {
            $this->I('topic_id', '动态话题ID', 'int', true, '动态话题ID不能为空');

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            if ($code !== Hint::SUCCESS) {
                break;
            }
            extract($variables); //数组参数化

            $ret = $this->trendsTopicModel->CUDTrendsTopic([], 'delete', $this->requestData['topic_id']);
            if (!$ret) {
                $code = Hint::ERR_DATA_REMOVE_FAIL;
                $msg = '动态话题' . Hint::getErrCodeMsg($code);
                break;
            }

            // 删除话题加入数据
            $this->trendsTopicModel->CUDTrendsTopicJoin([], 'delete', 0, $this->requestData['topic_id']);

        } while (false);

        return compact('code', 'msg', 'data');
    }

    ####################################################################################################

    /**
     * 获取多个用户信息
     *
     * @param array $data 二维数组
     * */
    private function getUserInfoByDataArray(&$data)
    {
        do {

            if (!isset($data[0]['user_id'])) {
                break;
            }

            $dataUserIds = array_column($data, 'user_id', 'user_id');

            // 用户信息
            $userDataArray = $this->user->get_users_by_ids($dataUserIds);
            // 用户钱包
            $userWalletDataArray = $this->financeUserWalletModel->get_wallets($dataUserIds);
            // 用户勋章
            $userMedalArray = $this->medalModel->getMedalUserListCache($dataUserIds, false);

            if (!empty($userDataArray)) {
                $userIds = array_column($userDataArray, 'user_id');
                $userKeyIds = array_column($userDataArray, 'user_id', 'user_id');

                $userWalletIds = array_column($userWalletDataArray, 'user_id');
                $userWalletKeyIds = array_column($userWalletDataArray, 'user_id', 'user_id');

                $userMedalIds = array_column($userMedalArray, 'user_id');
                $userMedalKeyIds = array_column($userMedalArray, 'user_id', 'user_id');

                foreach ($data as $key => $value) {
                    $data[$key]['user'] = [];

                    if (array_key_exists($value['user_id'], $userKeyIds)) {
                        $userDataIndex = array_search($value['user_id'], $userIds);
                        $data[$key]['user'] = $userDataArray[$userDataIndex];
                    }

                    if (array_key_exists($value['user_id'], $userWalletKeyIds)) {
                        $userWalletDataIndex = array_search($value['user_id'], $userWalletIds);
                        $data[$key]['user']['wealth_balance'] = $userWalletDataArray[$userWalletDataIndex]['wealth_balance'];
                        $data[$key]['user']['charm_balance'] = $userWalletDataArray[$userWalletDataIndex]['charm_balance'];
                        $data[$key]['user']['kk_balance'] = $userWalletDataArray[$userWalletDataIndex]['kk_balance'];
                        $data[$key]['user']['reputation_balance'] = $userWalletDataArray[$userWalletDataIndex]['reputation_balance'];
                        $data[$key]['user']['celebrity_balance'] = $userWalletDataArray[$userWalletDataIndex]['celebrity_balance'];
                        $data[$key]['user']['wealth_balance'] = $userWalletDataArray[$userWalletDataIndex]['wealth_balance'];
                        $data[$key]['user']['wealth_balance'] = $userWalletDataArray[$userWalletDataIndex]['wealth_balance'];
                    }

                    if (array_key_exists($value['user_id'], $userMedalKeyIds)) {
                        $userWalletDataIndex = array_search($value['user_id'], $userMedalIds);
                        $data[$key]['user']['medal'] = $userMedalArray[$userWalletDataIndex];
                    } else {
                        $data[$key]['user'] ['medal'] = [];
                    }

                    $data[$key]['is_follow'] = false;

                    continue;
                }
            } else {
                foreach ($data as $key => $value) {
                    $data[$key]['user'] = [];
                }
            }

        } while (false);

        $data = array_values($data);
    }

    /**
     * 动态 阅读数
     *
     * @param array $data 二维数组
     * */
    private function getTrendsReadCount(&$data)
    {
        do {
            if (!isset($data[0]['content_id'])) {
                break;
            }

            $contentIds = array_column($data, 'content_id', 'content_id');
            $trendsCountData = $this->trendsModel->trends_count($contentIds);

            if (!empty($trendsCountData)) {
                $trendsIds = array_column($trendsCountData, 'content_id');
                $trendsKeyIds = array_column($trendsCountData, 'content_id', 'content_id');

                foreach ($data as $key => $value) {
                    $data[$key]['read_count'] = 0;
                    $data[$key]['comment_count'] = 0;
                    $data[$key]['like_count'] = 0;
                    $data[$key]['share_count'] = 0;

                    if (array_key_exists($value['content_id'], $trendsKeyIds)) {
                        $trendsDataIndex = array_search($value['content_id'], $trendsIds);

                        $data[$key]['read_count'] = $trendsCountData[$trendsDataIndex]['read_count'];
                        $data[$key]['comment_count'] = $trendsCountData[$trendsDataIndex]['comment_count'];
                        $data[$key]['like_count'] = $trendsCountData[$trendsDataIndex]['like_count'];
                    }
                    continue;
                }
            } else {
                foreach ($data as $key => $value) {
                    $data[$key]['read_count'] = 0;
                    $data[$key]['comment_count'] = 0;
                    $data[$key]['like_count'] = 0;
                    $data[$key]['share_count'] = 0;
                    continue;
                }
            }

        } while (false);
    }

    /**
     * 动态 用户是否点赞
     *
     * @param array $data 二维数组
     * */
    private function getTrendsLikeExist(&$data)
    {
        do {
            $userInfo = $this->user->get_current_user();
            $userId = $userInfo['user_id'] ?? 0;

            if ($userId <= 0 or !isset($data[0]['content_id'])) {
                break;
            }

            $contentIds = array_column($data, 'content_id');
            foreach ($contentIds as $key => $value) {
                $data[$key]['is_like'] = $this->trendsModel->trends_like_exist($userId, $value);
            }

        } while (false);
    }
}